package com.cnswhy.cloud.server.app.controller.merchant;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.mybatis.conditions.query.QueryWrap;
import com.cnswhy.cloud.common.core.utils.AliUploadFileUtils;
import com.cnswhy.cloud.common.core.utils.Kits;
import com.cnswhy.cloud.common.core.utils.StrPool;
import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.core.dto.MerchSaveDTO;
import com.cnswhy.cloud.server.core.dto.MerchSearchDTO;
import com.cnswhy.cloud.server.core.entity.Customer;
import com.cnswhy.cloud.server.core.entity.Merch;
import com.cnswhy.cloud.server.core.entity.MerchSearchType;
import com.cnswhy.cloud.server.core.service.*;
import com.cnswhy.cloud.server.core.service.merchant.MerchantService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "落地商家")
@Controller
@RequestMapping("/merch")
@Slf4j
public class MerchantController extends BaseController {
    @Autowired
    IotChargingLineInfoService iotChargingLineInfoService;
    @Autowired
    IotChargingLineScaleService iotChargingLineScaleService;
    @Autowired
    MerchantService merchantService;
    @Autowired
    MerchService merchService;
    @Autowired
    MerchSearchTypeService merchSearchTypeService;
    @Autowired
    IotTerminalInfoService iotTerminalInfoService;
    @ApiOperation(value = "添加商家", httpMethod = "POST")
    @RequestMapping(value = "/save", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public RespVo save(HttpServletRequest request,
                       String merchSaveDTOList,
                       String key,
                       String area,
                       String radius ,
                       String addType ,
                       String type) {
        Customer customer = getLoginCustomer(request);
        String settDate = SystemClockUtil.getSettDateyyyyMMdd();
        settDate = settDate.substring(0,4) + "-"+ settDate.substring(5,6) + "-" + settDate.substring(7,8);
        int count = 0;
        try{
            log.info("type :{}", type);
            MerchSearchType merchSearchType = MerchSearchType.builder()
                    .addType(addType)
                    .customerId(customer.getId())
                    .searchType(type)
                    .searchRadius(radius)
                    .serarchArea(area)
                    .settDate(settDate)
                    .searchKey(key).build();
            merchSearchTypeService.save(merchSearchType);
            //type 1 高德  2 腾讯 3 百度 4 企查查
            JSONArray jsonArray = JSON.parseArray(merchSaveDTOList);
            for(Object object : jsonArray){
                MerchSaveDTO merchSaveDTO = new MerchSaveDTO();
                try {
                    if("1".equals(type)){
                        //高德
                        log.info(JSON.toJSONString(object));
                        JSONObject jsonObject =  JSON.parseObject(JSON.toJSONString(object));
                        merchSaveDTO.setName(jsonObject.getString("name"));
                        merchSaveDTO.setAddress(jsonObject.getString("address"));
                        merchSaveDTO.setCity(jsonObject.getString("cityname"));
                        merchSaveDTO.setProvince(jsonObject.getString("pname"));
                        merchSaveDTO.setArea(jsonObject.getString("adname"));
                        String location = jsonObject.getString("location");
                        try {
                            String[] sortArr = StrUtil.split(location, StrPool.COMMA);
                            String lat = sortArr[1];
                            String lng = sortArr[0];
                            merchSaveDTO.setLat(lat);
                            merchSaveDTO.setLng(lng);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        merchSaveDTO.setPcode(jsonObject.getString("pcode"));
                        merchSaveDTO.setCitycode(jsonObject.getString("citycode"));
                        merchSaveDTO.setAdcode(jsonObject.getString("adcode"));
                        merchSaveDTO.setTel(jsonObject.getString("tel"));
                        merchSaveDTO.setType(jsonObject.getString("type"));
                        merchSaveDTO.setTypecode(jsonObject.getString("typecode"));
                    }else if("2".equals(type)){
                        //腾讯
                        log.info(JSON.toJSONString(object));
                        JSONObject jsonObject =  JSON.parseObject(JSON.toJSONString(object));
                        merchSaveDTO.setName(jsonObject.getString("title"));
                        merchSaveDTO.setAddress(jsonObject.getString("address"));
                        merchSaveDTO.setProvince(jsonObject.getString("province"));
                        merchSaveDTO.setCity(jsonObject.getString("city"));
                        merchSaveDTO.setArea(jsonObject.getString("area"));
                        merchSaveDTO.setTel("[\"" + jsonObject.getString("tel") +"\"]");
                        merchSaveDTO.setType(jsonObject.getString("category"));
                        try {
                            JSONObject location = jsonObject.getJSONObject("location");
                            merchSaveDTO.setLat(location.getString("lat"));
                            merchSaveDTO.setLng(location.getString("lng"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            JSONObject ad_info = jsonObject.getJSONObject("ad_info");
                            merchSaveDTO.setArea(ad_info.getString("district"));
                            merchSaveDTO.setCity(ad_info.getString("city"));
                            merchSaveDTO.setProvince(ad_info.getString("province"));
                            merchSaveDTO.setAdcode(ad_info.getString("adcode"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else if("3".equals(type)){
                        //百度
                        log.info(JSON.toJSONString(object));
                        JSONObject jsonObject =  JSON.parseObject(JSON.toJSONString(object));
                        merchSaveDTO.setName(jsonObject.getString("name"));
                        merchSaveDTO.setAddress(jsonObject.getString("address"));
                        merchSaveDTO.setProvince(jsonObject.getString("province"));
                        merchSaveDTO.setCity(jsonObject.getString("city"));
                        merchSaveDTO.setArea(jsonObject.getString("area"));
                        //merchSaveDTO.setTel(jsonObject.getString("telephone"));
                        merchSaveDTO.setTel("[\"" + jsonObject.getString("telephone") +"\"]");

                        try {
                            JSONObject location = jsonObject.getJSONObject("location");
                            merchSaveDTO.setLat(location.getString("lat"));
                            merchSaveDTO.setLng(location.getString("lng"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else if("4".equals(type)){

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Merch merch = BeanUtil.toBean(merchSaveDTO, Merch.class);
                merch.setTel(null);
                merch.setPhone(null);
                String tel = merchSaveDTO.getTel();
                tel = tel.substring(tel.indexOf("[") + 1, tel.indexOf("]"));
                String[] abc = tel.split(",");
                tel = "";
                String phone = "";
                for (String string : abc) {
                    if(string.indexOf("-") >= 0){
                        tel = tel + string + ",";
                    }else{
                        phone = phone + string + ",";
                    }
                }
                if(tel.indexOf(",") > 0){
                    tel = tel.substring(0,tel.length() - 1);
                    merch.setTel("[" + tel +"]");

                }else{
                    merch.setTel("[]");
                }
                if(phone.indexOf(",")> 0){
                    phone = phone.substring(0,phone.length() - 1);
                    merch.setPhone("[" + phone +"]");
                }else{
                    merch.setPhone("[]");
                }
                merch.setCustomerId(customer.getId());
                merch.setSearchKey(key);
                merch.setSerarchArea(area);
                merch.setSearchRadius(radius);
                merch.setSearchType(type);
                merch.setSettDate(settDate);
                merch.setSearchId(merchSearchType.getId());
                merchService.save(merch);
                count ++;
            }
            merchSearchType.setCount(count);
            merchSearchTypeService.updateById(merchSearchType);
            return RespVo.success();
        } catch (BizException e) {
            return RespVo.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return RespVo.fail("添加商家失败");
        }
    }
    @ApiOperation(value = "查询list", httpMethod = "POST")
    @RequestMapping(value = "/list", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public RespVo list(HttpServletRequest request,@RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try{
            Customer customer = getLoginCustomer(request);
            Page<MerchSearchType> page = new Page<>(currentPage, pageSize);
            IPage<MerchSearchType> pageList = null;
            pageList = merchSearchTypeService.page(page, Wraps.<MerchSearchType>lbQ().eq(MerchSearchType::getCustomerId, customer.getId()).orderByDesc(MerchSearchType::getId));
            /*if(addType == null || addType == 0){
                pageList = merchSearchTypeService.page(page, Wraps.<MerchSearchType>lbQ().eq(MerchSearchType::getCustomerId, customer.getId()).orderByDesc(MerchSearchType::getId));
            }else{
                pageList = merchSearchTypeService.page(page, Wraps.<MerchSearchType>lbQ().eq(MerchSearchType::getCustomerId, customer.getId())
                        .eq(MerchSearchType::getAddType,addType).orderByDesc(MerchSearchType::getId));
            }*/

            return RespVo.success(pageList);
            /*Customer customer = getLoginCustomer(request);
            List<MerchSearchDTO> merchSearchDTOList = merchService.getSearch(customer.getId());
            return RespVo.success(merchSearchDTOList);*/
        } catch (BizException e) {
            return RespVo.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return RespVo.fail("添加商家失败");
        }
    }
    @ApiOperation(value = "查询list数据", httpMethod = "POST")
    @RequestMapping(value = "/getSearchData", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public RespVo getSearchData(HttpServletRequest request, @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam(name = "searchId") String searchId) {
        try{

            Customer customer = getLoginCustomer(request);
            Page<Merch> page = new Page<>(currentPage, pageSize);

            IPage<Merch> pageList = merchService.page(page,Wraps.<Merch>lbQ().eq(Merch::getCustomerId, customer.getId())
                    .eq(Merch::getSearchId,Long.valueOf(searchId))
                    //.eq(Merch::getSearchType,merchSearchDTO.getSearchType())
                    .orderByDesc(Merch::getId));
            return RespVo.success(pageList);
        } catch (BizException e) {
            return RespVo.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return RespVo.fail("添加商家失败");
        }
    }
    @ApiOperation(value = "查询list数据", httpMethod = "POST")
    @RequestMapping(value = "/exportXls", method = {RequestMethod.POST})
    @ResponseBody
    public RespVo exportExcel(MerchSearchDTO params, HttpServletRequest request) {
        // Step.1 组装查询条件
        /*String title = params.getMap().get("title");
        String type = params.getMap().getOrDefault("type", ExcelType.XSSF.name());
        String sheetName = params.getMap().getOrDefault("sheetName", "SheetName");*/

        ExcelType excelType =  ExcelType.XSSF ;
        ExportParams exportParams = new ExportParams("", "sheetName", excelType);

        Map<String, Object> map = new HashMap<>(5);
        Merch model = BeanUtil.toBean(params, Merch.class);
        QueryWrap<Merch> wrapper = model == null ? Wraps.q() : Wraps.q(model);
        map.put(NormalExcelConstants.DATA_LIST, merchService.list(wrapper));
        map.put(NormalExcelConstants.CLASS, Merch.class);
        map.put(NormalExcelConstants.PARAMS, exportParams);
        String fileName = "Merch" + Kits.Date.getyyyyMMddHHmmss() + ".xlsx";
        map.put(NormalExcelConstants.FILE_NAME, fileName);
        //PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Merch.class, merchService.list(wrapper));
        String filePool = "/tmp/fileSteam/";
        FileUtil.mkdir(filePool);
        String url = null;
        try {
            File f = new File(filePool + fileName);
            OutputStream os = null;
            os = new FileOutputStream(f);
            workbook.write(os);
            url = AliUploadFileUtils.updateExcelFileToOss(f, fileName);
            f.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", url);
        return RespVo.success(jsonObject);
    }
    private String getDbField(String beanField, Class<?> clazz) {
        Field field = ReflectUtil.getField(clazz, beanField);
        if (field == null) {
            return StrUtil.EMPTY;
        }
        TableField tf = field.getAnnotation(TableField.class);
        if (tf != null && StringUtils.isNotEmpty(tf.value())) {
            String str = tf.value();
            return str;
        }
        return StrUtil.EMPTY;
    }
    @ApiOperation(value = "查询商家", httpMethod = "POST")
    @RequestMapping(value = "/getMerchData", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public RespVo getMerchData(HttpServletRequest request, Long id) {
        try{

            return RespVo.success(merchService.getById(id));
        } catch (BizException e) {
            return RespVo.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return RespVo.fail("添加商家失败");
        }
    }

    public static void main(String[] args) {
        String str = "[\"13301209642\",\"010-87187371\",\"010-87187074\"]";
        String tel = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
        System.out.println(tel);
        String[] abc = tel.split(",");
        tel = "";
        String phone = "";
        for (String string : abc) {
            System.out.println(string);
            if(string.indexOf("-") >= 0){
                tel = tel + string + ",";
            }else{
                phone = phone + string + ",";
            }
        }
        tel = tel.substring(0,tel.length() - 1);
        phone = phone.substring(0,phone.length() - 1);
        System.out.println(tel);
        System.out.println(phone);
    }
}
